import 'package:flutter/material.dart';
import 'package:detect/utils/global.dart';

class ResizeStateBuilder extends StatefulWidget {
  final BuildContext parent;
  final Widget child;
  final Widget Function(BuildContext context, StateSetter stateSetter, Widget child)? builder;
  final bool resizeToAvoidBottomInset;

  const ResizeStateBuilder({super.key, required this.parent, required this.child, this.builder, this.resizeToAvoidBottomInset = false});

  @override
  State<ResizeStateBuilder> createState() => _ResizeStateBuilderState();
}

class _ResizeStateBuilderState extends State<ResizeStateBuilder> with WidgetsBindingObserver {
  EdgeInsets _paddingInsets = EdgeInsets.zero;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    if (widget.resizeToAvoidBottomInset) {
      RenderObject? renderObject = widget.parent.findRenderObject();
      if (renderObject is RenderBox && widget.parent.size != null) {
        RenderBox renderBox = renderObject;
        Offset offset = renderBox.localToGlobal(Offset.zero);
        EdgeInsets outset = EdgeInsets.only(
          left: offset.dx,
          top: offset.dy,
          right: Global.windowSize.width - widget.parent.size!.width - offset.dx,
          bottom: Global.windowSize.height - widget.parent.size!.height - offset.dy,
        );
        EdgeInsets insets = Global.windowInsets - outset;
        if (insets.left < 0) insets = insets.copyWith(left: 0);
        if (insets.top < 0) insets = insets.copyWith(top: 0);
        if (insets.right < 0) insets = insets.copyWith(right: 0);
        if (insets.bottom < 0) insets = insets.copyWith(bottom: 0);
        setState(() => _paddingInsets = insets);
      }
    }
  }

  @override
  Widget build(BuildContext context) => AnimatedPadding(
        padding: _paddingInsets,
        duration: const Duration(milliseconds: 300),
        curve: Curves.fastOutSlowIn,
        child: widget.builder?.call(context, setState, widget.child) ?? widget.child,
      );
}
